package com.example.orchid.paper.activity;

import android.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.ShareActionProvider;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.Window;
import android.widget.Toast;

import com.example.orchid.paper.PaperApplication;
import com.example.orchid.paper.R;
import com.example.orchid.paper.entity.NewsDetailEntity;
import com.example.orchid.paper.entity.NewsListEntity.NewsEntity;
import com.example.orchid.paper.fragment.NewsDetailFragment;
import com.example.orchid.paper.fragment.NewsDetailFragment.OnContentLoadListener;
import com.example.orchid.paper.task.MyAsyncTask;
import com.newgame.sdk.AndroidShare;

import java.util.List;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * 新闻详情页，Activity
 * Created by Orchid on 2015-10-13.
 */
@SuppressWarnings("ConstantConditions")
public class NewsDetailActivity extends BaseActivity implements OnContentLoadListener {
    //手指在屏幕滑动，X轴最小变化值
    private static final int FLING_MIN_DISTANCE_X = 200;

    //手指在屏幕滑动，Y轴最小变化值
    private static final int FLING_MIN_DISTANCE = 10;

    //手指在屏幕滑动，最小速度
    private static final int FLING_MIN_VELOCITY = 1;

    private GestureDetector mGestureDetector;

    private long mNewsId = 0;
    private NewsEntity mNewsEntity = null;
    private NewsDetailEntity mNewsDetailEntity = null;

    private boolean isInFavorite = false;

    private Menu mOptionsMenu;
    private MenuItem mFavActionItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
        super.onCreate(savedInstanceState);


        supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setBackgroundDrawable(
                getResources().getDrawable(R.drawable.ab_bg_black));

        ShareSDK.initSDK(this);
        mGestureDetector = new GestureDetector(this, mOnGestureListener);

        if (savedInstanceState == null) {
            Uri data = getIntent().getData();
            String scheme = data != null ? data.getScheme() : "";// "http"
            String host = data != null ? data.getHost() : "";// "daily.zhihu.com"
            List<String> params = data != null ? data.getPathSegments() : null;

            if (scheme.equals("http") && host.equals("daily.zhihu.com")
                    && params != null && params.size() == 2) {
                String storyId = params.get(1);
                mNewsId = Long.parseLong(storyId);
            } else {
                mNewsId = getIntent().getLongExtra("id", 0);
                mNewsEntity = (NewsEntity) getIntent().getSerializableExtra("newsEntity");
            }

        } else {
            mNewsEntity = (NewsEntity) savedInstanceState.getSerializable("newsEntity");
            mNewsId = savedInstanceState.getLong("newsID");
        }

        Bundle bundle = new Bundle();
        bundle.putLong("id", mNewsId);

        // Add the Sample Fragment if there is one
        Fragment newFragment = getFragment();
        newFragment.setArguments(bundle);

        if (newFragment != null) {
            getFragmentManager().beginTransaction().replace(android.R.id.content, newFragment).commit();

        }

        new FavoriteStatusGetTask().executeOnExecutor(MyAsyncTask.THREAD_POOL_EXECUTOR);
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();

        updateCreateMenu();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putLong("newsId", mNewsId);
        outState.putSerializable("newsEntity", mNewsEntity);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        mOptionsMenu = menu;

        getMenuInflater().inflate(R.menu.share_action_provider, menu);
        mFavActionItem = menu.findItem(R.id.menu_item_fav_action_bar);
        if (isInFavorite) {
            mFavActionItem.setIcon(R.drawable.ab_fav_active);
            mFavActionItem.setTitle(R.string.actionbar_item_fav_cancel);
        } else {
            mFavActionItem.setIcon(R.drawable.ab_fav_normal);
            mFavActionItem.setTitle(R.string.actionbar_item_fav_add);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_item_fav_action_bar: {
                if (isInFavorite) {
                    PaperApplication.getNewsFavoriteDataSource().deleteFromFavorite(String.valueOf(mNewsId));

                    Toast.makeText(this, R.string.fav_cancel_success, Toast.LENGTH_SHORT).show();

                    mFavActionItem.setIcon(R.drawable.ab_fav_normal);
                    mFavActionItem.setTitle(R.string.actionbar_item_fav_add);

                    isInFavorite = false;
                } else {
                    String title = null, image = null, share_url = null;

                    if (mNewsDetailEntity != null) {
                        title = mNewsDetailEntity.title;
                        image = mNewsDetailEntity.image;
                        share_url = mNewsDetailEntity.share_url;
                    } else if (mNewsEntity != null) {
                        title = mNewsEntity.title;
                        image = mNewsEntity.images.get(0);
                        share_url = mNewsEntity.share_url;
                    }

                    if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(share_url)) {
                        PaperApplication.getNewsFavoriteDataSource().add2Favorite(
                                String.valueOf(mNewsId), title, image, share_url);

                        Toast.makeText(this, R.string.fav_add_success, Toast.LENGTH_LONG).show();

                        mFavActionItem.setIcon(R.drawable.ab_fav_active);
                        mFavActionItem.setTitle(R.string.actionbar_item_fav_cancel);

                        isInFavorite = true;
                    } else {
                        Toast.makeText(this, R.string.fav_add_fail, Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            }
            case R.id.menu_item_share_action_provider_action_bar: {
                showShare();
                break;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected Fragment getFragment() {
        return new NewsDetailFragment();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private OnGestureListener mOnGestureListener = new OnGestureListener() {
        @Override
        public boolean onDown(MotionEvent e) {
            return false;
        }

        @Override
        public void onShowPress(MotionEvent e) {

        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return false;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e) {

        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean isXWell = Math.abs(e2.getX() - e1.getX()) < FLING_MIN_DISTANCE_X;

            if (isXWell && e1.getY() - e2.getY() > FLING_MIN_DISTANCE && Math.abs(velocityY) > FLING_MIN_VELOCITY) {
                getSupportActionBar().hide();
            } else if (isXWell && e2.getY() - e1.getY() > FLING_MIN_DISTANCE && Math.abs(velocityY) > FLING_MIN_VELOCITY) {
                getSupportActionBar().show();
            }
            return false;
        }
    };

    @Override
    public void onComplete(NewsDetailEntity newsDetailEntity) {
        mNewsDetailEntity = newsDetailEntity;
        updateCreateMenu();

    }

    private class FavoriteStatusGetTask extends MyAsyncTask<Void, Void, Boolean> {

        @Override
        protected Boolean doInBackground(Void... params) {
            return PaperApplication.getNewsFavoriteDataSource().isInFavorite(String.valueOf(mNewsId));
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);

            isInFavorite = aBoolean;
            updateCreateMenu();
        }
    }

    private void updateCreateMenu() {
        if (Build.VERSION.SDK_INT >= 11) {
            invalidateOptionsMenu();
        } else if (mOptionsMenu != null) {
            mOptionsMenu.close();
            onCreateOptionsMenu(mOptionsMenu);
        }
    }

    private Intent prepareIntent() {
        Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

        if (mNewsDetailEntity != null) {
            StringBuilder sb = new StringBuilder();
            sb.append(mNewsDetailEntity.title).append(" ").append(mNewsDetailEntity.share_url);
            shareIntent.putExtra(Intent.EXTRA_TEXT, sb.toString());
        } else if (mNewsEntity != null) {
            StringBuilder sb = new StringBuilder();
            sb.append(mNewsEntity.title).append(" ").append(mNewsEntity.share_url);
            shareIntent.putExtra(Intent.EXTRA_TEXT, sb.toString());
        }

        return shareIntent;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        mGestureDetector.onTouchEvent(ev);

        return super.dispatchTouchEvent(ev);
    }

    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(mNewsDetailEntity.title);
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl(mNewsDetailEntity.share_url);
        // text是分享文本，所有平台都需要这个字段
        oks.setText(mNewsDetailEntity.title + mNewsDetailEntity.share_url);
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oks.setImageUrl(mNewsDetailEntity.image);//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(mNewsDetailEntity.share_url);
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://QQ.cn");
// 启动分享GUI
        oks.show(this);
    }
}
